package cn.iocoder.yudao.module.trade.job.order;


import cn.hutool.core.util.RandomUtil;
import cn.iocoder.yudao.framework.quartz.core.handler.JobHandler;
import cn.iocoder.yudao.framework.tenant.core.job.TenantJob;
import cn.iocoder.yudao.module.trade.service.order.TradeOrderUpdateService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import static cn.hutool.core.util.NumberUtil.isLong;

/**
 * 定时任务，每天晚上10点生成指定金额范围内的随机订单数据。
 *
 * @author wu.mingqun
 */
@Component
public class TraderOrderAutoCreateOrdersJob implements JobHandler {

    @Resource
    private TradeOrderUpdateService tradeOrderUpdateService;

    @Value("${trade.order.auto-create.store-ids}")
    private String storeIdsURL;

    @Value("${trade.order.auto-create.turnover.min}")
    private int turnover_min;

    @Value("${trade.order.auto-create.turnover.max}")
    private int turnover_max;



    @Override
    @TenantJob
    public String execute(String param) {
        // 生成订单数据
        // 读取配置文件，获取商铺ID列表
        String[] storeIds = storeIdsURL.split(",");
        List<String> validStoreIds = Arrays.stream(storeIds)
                .filter(id -> id != null && !id.trim().isEmpty() && isLong(id))
                .collect(Collectors.toList());

        if (validStoreIds.isEmpty()) {
            return "success";
        }
        LocalDateTime date = LocalDateTime.now(); // 当前日期

        for (String storeIdStr : storeIds) {
            Long storeId = Long.parseLong(storeIdStr);
            // 随机生成订单金额
            int turnover = RandomUtil.randomInt(turnover_min, turnover_max); // 订单金额范围
            tradeOrderUpdateService.insertOrders(turnover,date,storeId);

        }

        return "success";
    }
}
